<template>
  <div>
    <el-card shadow="hover" class="layout-padding-auto">
      <!-- <TableSearch :search="state.search" @search="onSearch" @listenClick="listenClick" /> -->
      <el-row>
        <el-col :span="18">
          <el-input
            style="width: 30%"
            v-model="search.keyword"
            placeholder="可输入故障类型搜索"
          />
          <span style="margin-left: 10px">设备类型</span>
          <a-tree-select
            v-model:value="deviceTypes"
            style="
              margin: 5px 0;
              width: 300px;
              font-size: var(--el-font-size-base);
            "
            show-search
            placeholder="请选择"
            allow-clear
            multiple
            :maxTagCount="4"
            tree-default-expand-all
            :tree-data="cascaderData"
            :fieldNames="cascaderPropsAut"
            @change="cascaderChange"
          >
            <template #title="{ value: val, configValue }">
              {{ configValue }}
            </template>
          </a-tree-select>
          <el-button style="margin-left: 10px" type="primary" @click="searchFor"
            >搜索</el-button
          >
          <el-button type="primary" plain @click="resetFor">重置</el-button>
        </el-col>
        <el-col :span="6" style="text-align: right">
          <el-button
            type="primary"
            @click="add"
            v-if="buttonDisplayOrNot(buttonCodes, 'gzxAddBtn')"
            >新增</el-button
          >
          <el-button
            type="primary"
            plain
            @click="debounce(batchImportDevice, 1000)"
            v-if="buttonDisplayOrNot(buttonCodes, 'gzxBatchImportBtn')"
            >批量导入</el-button
          >
          <el-button
            type="primary"
            plain
            @click="debounce(importTemplateDownload, 1000)"
            v-if="buttonDisplayOrNot(buttonCodes, 'gzxImportTemplateBtn')"
            >导入模板下载</el-button
          >
        </el-col>
      </el-row>
      <Table
        ref="tableRef"
        v-bind="state.tableData"
        class="table-demo"
        @delRow="onTableDelRow"
        @pageChange="onTablePageChange"
        @listenClick="listenClick"
      >
        <template #default="{ slotData, slotColumn }">
          <div v-if="slotColumn.key === 'isSupport'">
            {{ slotData.isSupport }}
          </div>
        </template>
      </Table>
      <AddChildren
        :childrenDialog="childrenDialog"
        :childrenTitle="childrenTitle"
        :childrenForm="childrenForm"
        @childrenCancel="childrenCancel"
        @childrenSubmit="childrenSubmit"
      >
      </AddChildren>
      <FailureDialog
        :failureDialog="failureDialog"
        :failureTitle="failureTitle"
        :failureForm="failureForm"
        @failureCancel="failureCancel"
        @failureSubmit="failureSubmit"
      >
      </FailureDialog>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { ref, reactive, defineAsyncComponent, onMounted } from 'vue'
import { dictionaryList } from '/@/api/publicApi'
import {
  deleteFailureTermApi,
  importFailureTermApi,
  repairDownloadMouldApi
} from '/@/api/repair'
import { buttonDisplayOrNot } from '../../utils/buttonBoolean'
import { debounce } from '/@/utils/loading'
import { getButtonListByRoleApi } from '/@/api/publicApi'
import { Session } from '/@/utils/storage'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const AddChildren = defineAsyncComponent(
  () => import('./components/AddChildren.vue')
)
const FailureDialog = defineAsyncComponent(
  () => import('./components/FailureDialog.vue')
)
// 定义变量内容
const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'deviceTypeName', colWidth: '', title: '设备类型', type: 'text' },
      { key: 'failureName', colWidth: '', title: '故障类型', type: 'text' }
      // { key: 'image', colWidth: '', width: '70', height: '40', title: '图片描述', type: 'image' },
    ],
    columnBtn: [
      {
        name: 'addChildren',
        text: '新增子项',
        hide(row: any): boolean {
          return true
        },
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'gzxAddItemBtn'
      },
      {
        name: 'edit',
        text: '编辑',
        hide(row: any): boolean {
          return true
        },
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'gzxEditBtn'
      },
      {
        name: 'del',
        text: '删除',
        hide(row: any): boolean {
          return true
        },
        type: 'danger',
        btns: buttonCodes.value,
        btnCode: 'gzxDeleteBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/deviceFailureTerm/failureTermList',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: true, // 是否可以扩展
      operateWidth: '400' //操作栏宽度
    },
    // 搜索参数
    param: {
      type: 1 // 必传参数，分页的不要传
    },
    extendTable: {
      // 二级表格
      header: [
        { key: 'failureName', colWidth: '', title: '故障现象', type: 'text' },
        { key: 'solution', colWidth: '', title: '解决方案', type: 'text' }
      ], // 第二级的头部
      dataProp: 'phenomenonList', // 第二级的数据字段
      isOperate: true, // 是否显示表格操作栏
      extendBtn: [
        {
          name: 'editItem',
          text: '编辑',
          hide(row: any): boolean {
            return true
          },
          type: 'primary',
          btns: buttonCodes.value,
          btnCode: 'gzxEditBtn'
        },
        {
          name: 'delItem',
          text: '删除',
          hide(row: any): boolean {
            return true
          },
          type: 'danger',
          btns: buttonCodes.value,
          btnCode: 'gzxDeleteBtn'
        }
      ]
    }
  }
})

const search = ref({
  keyword: '',
  deviceTypes: []
})
const cascaderData = ref([])
const cascaderPropsAut = {
  value: 'id',
  label: 'configValue',
  children: 'children'
}

const searchFor = () => {
  state.tableData.param = Object.assign({}, state.tableData.param, {
    ...search.value
  })
  state.tableData.flash = !state.tableData.flash
}

const resetFor = () => {
  search.value.keyword = ''
  search.value.deviceTypes = []
  deviceTypes.value = []
  searchFor()
}

const deviceTypes = ref<any>([])
const cascaderChange = (val: any) => {
  search.value.deviceTypes = val
}

const getDeviceType = () => {
  dictionaryList({ configType: 'device_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      cascaderData.value = res.data
    }
  })
}
getDeviceType()

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}
// 删除当前项回调
const onTableDelRow = (row: EmptyObjectType) => {
  ElMessage.success(`删除${row.name}成功！`)
  getTableData()
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}

const gzName = ref('')
const onExpandChange = (val: any) => {
  gzName.value = val.failureName
}

const childrenDialog = ref(false)
const failureDialog = ref(false)
const childrenForm = ref({})
const failureForm = ref({})
const failureTitle = ref('')
const childrenTitle = ref('')
const addChildren = (row: any) => {
  childrenForm.value = row
  Reflect.set(childrenForm.value, 'gzName', row.failureName)
  childrenTitle.value = '新增'
  childrenDialog.value = !childrenDialog.value
}
const editItem = (row: any) => {
  childrenForm.value = row
  Reflect.set(childrenForm.value, 'gzName', row.parentName)
  console.log(childrenForm.value)
  childrenTitle.value = '编辑'
  childrenDialog.value = !childrenDialog.value
}

const add = () => {
  failureForm.value = {}
  failureTitle.value = '新增'
  failureDialog.value = !failureDialog.value
}

const edit = (row: any) => {
  failureForm.value = row
  failureTitle.value = '编辑'
  failureDialog.value = !failureDialog.value
}
const failureCancel = (row: any) => {
  failureDialog.value = !failureDialog.value
}
const failureSubmit = (row: any) => {
  getTableData()
  failureDialog.value = !failureDialog.value
}
const childrenCancel = () => {
  childrenDialog.value = !childrenDialog.value
}
const childrenSubmit = () => {
  getTableData()
  childrenDialog.value = !childrenDialog.value
}

const del = (row: any) => {
  ElMessageBox.confirm('确定删除该条内容?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteFailureTermApi(row.id).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          getTableData()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

const delItem = (row: any) => {
  del(row)
}

const importTemplateDownload = () => {
  repairDownloadMouldApi().then((res: any) => {
    let blob = new Blob([res], {
      type: 'application/vnd.ms-excel;charset=UTF-8'
    })
    let url = window.URL.createObjectURL(blob)
    const link = document.createElement('a') // 创建a标签
    link.download = '故障项导入模板.xls'
    link.href = url
    link.click()
    URL.revokeObjectURL(url) // 释放内存
  })
}

const batchImportDevice = () => {
  const fileType = ['xls', 'xlsx']
  const inputFile = document.createElement('input') as any
  inputFile.type = 'file'
  inputFile.style.display = 'none'
  document.body.appendChild(inputFile)
  inputFile.click()
  inputFile.addEventListener('change', () => {
    console.log('inputFile', inputFile)
    let file = inputFile.files[0]
    var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)

    if (!fileType.includes(testmsg)) {
      ElMessage.warning('上传的文件格式只能是excel文档')
      document.body.removeChild(inputFile)
      return false
    }

    let fd = new FormData()
    fd.append('file', file)
    let files = fd

    //上传接口
    importFailureTermApi(files).then((res) => {
      if (res.code == 0) {
        ElNotification({
          title: '故障项导入成功',
          message: '',
          type: 'success'
        })
        getTableData()
      }
    })
  })
}
//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  addChildren: addChildren,
  del: del,
  add: add,
  edit: edit,
  editItem: editItem,
  delItem: delItem,
  onExpandChange: onExpandChange,
  importTemplateDownload: importTemplateDownload,
  batchImportDevice: batchImportDevice
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}

onMounted(() => {
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/repair/FaultItem') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
</script>
<style scoped lang="scss"></style>
